<?
/**
 * Copyright 2007 Melange.
 *
 * This file is part of PHP-MELANGE.
 *
 * PHP-MELANGE is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * PHP-MELANGE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with PHP-MELANGE; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category    Melange
 * @package     php-melange
 * @subpackage  cms
 * @copyright   Copyright (c) 2007 Jeroen Simons. All rights reserved
 * @author      Jeroen Simons <jeroen@melange.nl>
 * @link        http://www.melange.nl/
 *
 */

require_once("mvc/action/Action.php");
require_once("cms/user/om/UserPeer.php");
require_once("cms/user/om/UserRolePeer.php");

class SaveAction extends Action {

    private $log;

    public function __construct() {
        $this->log =& LoggerManager::getLogger("SaveAction");
    }

    public function execute(ActionConfig &$mapping, &$form, Request &$request, Response &$response) {

        $errors = new ActionMessages();

        $user =& $form->getUser();
        $roles =& $form->getRoles();

        $conn = Propel::getConnection();

        try {

            $conn->begin();

            // Username taken check
            $c = new Criteria();
            $c->add(UserPeer::USERNAME, $user->getUsername());
            if($user->getUserId() > 0)
                $c->add(UserPeer::USER_ID, $user->getUserId(), Criteria::NOT_EQUAL);
            $check = UserPeer::doSelectOne($c, $conn);

            if(!is_null($check)) {
                $errors->add("user->username",
                    new ActionMessage("error.username.taken", true));
                $this->saveErrors($request, $errors);
                return $mapping->getInputForward();
            }

            if($user->getUserId() > 0) {

                // Retrieve the old user
                $olduser = UserPeer::retrieveByPk($user->getUserId(), $conn);

                // Delete the old roles
                $c = new Criteria();
                $c->add(UserRolePeer::USERNAME, $olduser->getUsername());
                UserRolePeer::doDelete($c, $conn);

                // Update user
                $c = new Criteria();
                $c->add(UserPeer::USER_ID, $user->getUserId());
                $c->add(UserPeer::USERNAME, $user->getUsername());
                $c->add(UserPeer::MODIFIED_DATE, date(_Core::FORMAT_SQLDATETIME));

                if(strlen($user->getPassword()) > 0 && strlen($form->getPassword2()) > 0)
                    $c->add(UserPeer::PASSWORD, md5($user->getPassword()));

                UserPeer::doUpdate($c, $conn);

            } else {

                $user->setActive(true);
                $user->setModifiedDate(date(_Core::FORMAT_SQLDATETIME));
                $user->setPassword(md5($user->getPassword()));
                $user->setInsertDate(date(_Core::FORMAT_SQLDATETIME));
                UserPeer::doInsert($user, $conn);

            }

            // Insert the user roles
            foreach($roles as $role) {
                $userRole = new UserRole();
                $userRole->setUsername($user->getUsername());
                $userRole->setRolename($role);
                UserRolePeer::doInsert($userRole, $conn);
            }

            $conn->commit();

        } catch(PropelException $e) {
            $conn->rollback();
            $errors->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("error.save", true));
            $this->log->error($e->getMessage());
        }

        // Return any save errors.
        if(!$errors->isEmpty()) {
            $this->saveErrors($request, $errors);
            return $mapping->getInputForward();
        }


        // Reset the userListForm from & to session.
        $session  = $request->getSession();
        $listForm = $session->getAttribute("php-cms/userListForm");
        $listForm->setPage(0);
        $session->setAttribute("php-cms/userListForm", $listForm);


        // To the success user.
        return $mapping->findForward("success");

    }

}
?>